package middleware

import (
	"gitee.com/DonHz/qimi/bluebell/controller"
	"gitee.com/DonHz/qimi/bluebell/util/jwt"
	"github.com/gin-gonic/gin"
	"strings"
)


func JWTAuthMiddleware() func(c *gin.Context) {
	return func(c *gin.Context) {
		// 客户端携带token的三种方式：请求头、请求体、URI
		// Get请求没有请求体，URI容易被看见
		authHeader:=c.Request.Header.Get("Authorization")
		if authHeader == "" {
			controller.ResponseError(c, controller.CodeNeedLogin)
			c.Abort()
			return
		}
		parts:=strings.SplitN(authHeader, " ", 2)
		if !(len(parts)==2 && parts[0]=="Bearer") {
			controller.ResponseError(c, controller.CodeInvalidToken)
			c.Abort()
			return
		}
		uc, err:= jwt.ParseToken(parts[1])
		if err!=nil {
			controller.ResponseError(c, controller.CodeInvalidToken)
			c.Abort()
			return
		}
		c.Set(controller.CtxUserIdKey, uc.UserId)
		c.Next()
	}
}
